package com.itheima.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.mapper.EmpExprMapper;
import com.itheima.mapper.EmpMapper;
import com.itheima.pojo.*;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.IOException;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class EmpServiceImpl extends ServiceImpl<EmpMapper,Emp> implements EmpService {

    @Autowired
    private EmpExprService empExprService;


    @Override
    @Transactional(rollbackFor = Exception.class)
    public void saveEmp(Emp emp) {
        //思路：保存员工，保存员工工作经历
        emp.setCreateTime(LocalDateTime.now());
        emp.setUpdateTime(LocalDateTime.now());
        emp.setPassword("123456");
        //mybatisplus里面，只要调用过save相关的方法之后，这个对象就自动有id了
        this.save(emp);
        //其他代码
        List<EmpExpr> exprList = emp.getExprList();
        //保存员工工作经历
        if(exprList!=null&&exprList.size()>0){
            exprList.forEach(e->e.setEmpId(emp.getId()));
            empExprService.saveBatch(exprList);
        }
    }

    @Override
    public Emp getEmpById(Integer id) {
        //查询emp
        Emp emp = this.getById(id);
        if(emp==null){
            //说明数据可能被删了
            throw new RuntimeException("数据不存在");
        }
        //查询工作经历，手里只有emp的id
        //sql：select * from emp_expr where emp_id = ?
        List<EmpExpr> list = empExprService.list(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId, emp.getId()));
        emp.setExprList(list);
        return emp;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateEmp(Emp emp) {
        //干什么？
        //1.修改员工
        //2.修改员工工作经历，但是这个工作经历是多条，所以我们一般先全删，再新增
        emp.setUpdateTime(LocalDateTime.now());
        this.updateById(emp);
        //sql：delete from emp_expr where emp_id = ?条件删除
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().eq(EmpExpr::getEmpId,emp.getId()));

        //新增
        List<EmpExpr> exprList = emp.getExprList();
        if(exprList!=null&&exprList.size()>0){
            exprList.forEach(e->e.setEmpId(emp.getId()));
            empExprService.saveBatch(exprList);
        }
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void deleteEmpByIds(List<Integer> ids) {
        //干什么事？删除员工，删除员工的工作经历
        this.removeByIds(ids);

        //sql：delete from emp_expr where emp_id in ()
        empExprService.remove(new LambdaQueryWrapper<EmpExpr>().in(EmpExpr::getEmpId,ids));

    }
}
